package com.app.qbake.module.login;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.app.qbake.MainActivity;
import com.app.qbake.R;
import com.app.qbake.RuntimeRationale;
import com.app.qbake.module.login.di.SplashComponent;
import com.app.qbake.module.login.layout.GetVipStatusLayout;
import com.app.qbake.module.login.mvp.SplashView;
import com.app.qbake.module.login.presenter.SplashPresenter;
import com.app.qbake.util.Stopwatch;
import com.wind.base.C;
import com.wind.base.mvp.view.DaggerMvpFragment;
import com.wind.base.repo.ConfigRepo;
import com.wind.base.request.BaseRequest;
import com.wind.base.utils.ActivityUtil;
import com.wind.base.utils.AppUtil;
import com.wind.base.utils.ViewInflater;
import com.wind.coder.annotations.Api;
import com.wind.coder.annotations.Heros;
import com.wind.coder.annotations.Param;
import com.wind.data.login.SplashRequest;
import com.wind.data.login.SplashResponse;
import com.yanzhenjie.permission.AndPermission;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by wind on 2018/9/4.
 */

@Heros(
        param = @Param(
                viewCanonicalName = "com.app.qbake.module.login.mvp.SplashView",
                responseCanonicalName = "com.wind.data.login.SplashResponse",
                requestCanonicalName = "com.wind.data.login.SplashRequest"

        ),
        api = @Api(httpMethod = Api.HttpMethod.GET, url = "config")
)
public class SplashFragment extends DaggerMvpFragment<SplashView, SplashPresenter, SplashComponent> implements SplashView {

    @BindView(R.id.layout_loading)
    ezy.ui.layout.LoadingLayout layout_loading;
    Stopwatch mStopwatch;
    @BindView(R.id.iv)
    ImageView iv;
    @Inject
    SplashPresenter presenter;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_splash;
    }

    @Override
    public SplashPresenter createPresenter() {
        return presenter;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //获取vip状态
        GetVipStatusLayout layout = new GetVipStatusLayout(getActivity());
        layout.getVipStatus();
        presenter.execute(buildSplashRequest());
        layout_loading.showContent();
        mStopwatch = new Stopwatch();
        String startPage = ConfigRepo.getInstance().get(getActivity()).getStart_page();
        if (!TextUtils.isEmpty(startPage)) {
            ViewInflater.inflateImage(iv, startPage);
        }

        layout_loading.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                layout_loading.showLoading();
                presenter.execute(buildSplashRequest());
            }
        });

        AndPermission.with(this)
                .runtime()
                .permission(Manifest.permission.ACCESS_WIFI_STATE,
                        Manifest.permission.CHANGE_WIFI_STATE)
                .rationale(new RuntimeRationale())

                .start();


    }

    private BaseRequest buildSplashRequest() {
        SplashRequest request = new SplashRequest();
        request.setPing("false");
        boolean isNormalUser = AppUtil.isPackageInstalled(getActivity(), C.Pack.PACK_NAME_WEIXIN);
        //boolean isNormalUser = isNormalUser();
        if (isNormalUser) {
            request.setIs_wechat(0);
        } else {
            request.setIs_wechat(1);
        }
        request.setDevices(AppUtil.getDeviceBrand());

        request.setTime_zone(getTimeZone());

        return request;
    }

    /**
     * 是否是普通用户
     * @return
     */
    private boolean isNormalUser() {
        List<String> videoApps = new ArrayList<>();
        videoApps.add(C.Pack.PACK_NAME_YOUKU);
        videoApps.add(C.Pack.PACK_NAME_QIYI);
        videoApps.add(C.Pack.PACK_NAME_HUYA);
        videoApps.add(C.Pack.PACK_NAME_DOUYIN);
        videoApps.add(C.Pack.PACK_NAME_QQLIVE);
        videoApps.add(C.Pack.PACK_NAME_DOUYU);
        int videoAppsCount = 0;
        for (int i = 0; i < videoApps.size(); i++) {
            boolean installed = AppUtil.isPackageInstalled(getActivity(), videoApps.get(i));
            if (installed) {
                videoAppsCount++;
            }
        }
        if (videoAppsCount>=3){
            return true;
        }
        List<String> tripApps = new ArrayList<>();
        tripApps.add(C.Pack.PACK_NAME_DIDI);
        tripApps.add(C.Pack.PACK_NAME_MOBIKE);
        tripApps.add(C.Pack.PACK_NAME_BAIDU_MAP);
        tripApps.add(C.Pack.PACK_NAME_GD_MAP);
        int tripAppsCount = 0;
        for (int i = 0; i < tripApps.size(); i++) {
            boolean installed = AppUtil.isPackageInstalled(getActivity(), tripApps.get(i));
            if (installed) {
                tripAppsCount++;
            }
        }
        if (tripAppsCount>=2){
            return true;
        }
        List<String> buyApps = new ArrayList<>();
        buyApps.add(C.Pack.PACK_NAME_TAOBAO);
        buyApps.add(C.Pack.PACK_NAME_TMALL);
        buyApps.add(C.Pack.PACK_NAME_JD);
        buyApps.add(C.Pack.PACK_NAME_MEITUAN);
        buyApps.add(C.Pack.PACK_NAME_ELE);
        int buyAppsCount = 0;
        for (int i = 0; i < buyApps.size(); i++) {
            boolean installed = AppUtil.isPackageInstalled(getActivity(), buyApps.get(i));
            if (installed) {
                buyAppsCount++;
            }
        }
        if (buyAppsCount>=2){
            return true;
        }

        if (videoAppsCount>=1&&tripAppsCount>=1&&buyAppsCount>=1){
            return true;
        }
        return false;
    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        layout_loading.showError();
    }

    @Override
    public void onSuccess(SplashResponse response) {
        ViewInflater.inflateImage(iv, response.getData().getStart_page());
        ConfigRepo.getInstance().store(getActivity(), response.getData());
        while (mStopwatch.elapseTime() < 2) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        MainActivity.start(getActivity());
        ActivityUtil.finish(getActivity());
    }

    public String getTimeZone() {
        return TimeZone.getDefault().getID();// Asia/Shanghai
    }
}
